<template>
  <div class="page customs" :style="{minHeight:docHeight}">
    <LeftSideBar></LeftSideBar>
    <div class="content-main clearfix">
      <ELHeader></ELHeader>
      <div class="right-content clearfix">
        <div class="breadcrumb">
          <el-breadcrumb separator=">">
            <i class="bread-ico">
              <icon name="wpexplorer"></icon>
            </i>
            <el-breadcrumb-item :to="{ path: '/' }">
              首页
            </el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/normal-customs' }" v-if="routeName === 'normal-customs'">普通客户列表</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/social-customs' }" v-if="routeName === 'social-customs'">普通客户列表</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/customs/'+customId }" v-if="routeName === 'customsDt'">客户详情</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/customs/'+customId+'/edit' }" v-if="routeName === 'editCustom'">客户编辑</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="btn-group">
          <el-button @click="uploadDialog = true" class="filter-item" size="small">批量上传</el-button>
          <el-button @click="showExportFilter = !showExportFilter" class="filter-item" size="small">批量导出</el-button>
        </div>
        <div class="tabpane-container" ref="tabpaneContainer" v-loading.body="loading" element-loading-text="拼命加载中" element-loading-customClass="partloading">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="普通客户列表" name="normal-customs">
              <Customs type = "1" v-if="routeName === 'normal-customs' && !switchSite" @changeLoading="changeLoading" :tabHeight="tabHeight"></Customs>
            </el-tab-pane>
            <el-tab-pane label="社交客户列表" name="social-customs">
              <Customs type = "0"  v-if="routeName === 'social-customs'" @changeLoading="changeLoading" :tabHeight="tabHeight"></Customs>
            </el-tab-pane>
            <el-tab-pane ref="detailContainer" v-if="routeName === 'customsDt' || routeName === 'editCustom'" label="客户详情" name="customsDt">
              <CustomProfile v-if="routeName === 'customsDt'" @changeLoading="changeLoading" :tabHeight="tabHeight"></CustomProfile>
            </el-tab-pane>
            <el-tab-pane ref="editContainer" v-if="routeName === 'editCustom'" label="编辑客户" name="editCustom" class="scroll" :style="'height:' + (this.tabHeight + 80) + 'px;'">
              <EditCustom v-if="routeName === 'editCustom'" @changeLoading="changeLoading"></EditCustom>
            </el-tab-pane>
            <el-tab-pane label="导出客户列表" name="export-customs">
              <ExportCustoms type = "1" v-if="routeName === 'export-customs' && !switchSite" @changeLoading="changeLoading" :tabHeight="tabHeight" :timeStamp="exportTime"></ExportCustoms>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <el-dialog title="上传文件" v-model="uploadDialog" top="6%">
        <el-upload v-if="uploadDialog"
          ref="upload"
          accept=".xls, .xlsx"
          class="upload-wrap"
          :action="uploadAction"
          name="upload_file"
          :on-success="succesUpload"
          :on-error="failedUpload">
          <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              <p>选择要上传的文件，仅支持xls格式, 文件名不能相同,下载<a style="color:#20a0ff;" :href="'http://oodoa7x5e.bkt.clouddn.com/CRM%E6%89%B9%E9%87%8F%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xls?' + Math.random()">「模板」</a></p>
              <div class="import-results">
                  <div class="import-item" v-for="(obj, index, i) in responseList">
                    <h4 v-if="obj.error" class="error"><b style="font-size:14px;">{{ i + 1 }}</b> &nbsp;批量导入 「{{obj.file.name}}」 失败! <span v-if="obj.msg">「{{ obj.msg }}」</span></h4>
                    <h4 v-if="!obj.error"><b style="font-size:14px;">{{ i + 1 }}</b> &nbsp;上传 「 {{obj.file.name}} 」 成功, 导入结果如下: </h4>
                    <el-table :show-header="showHeader" v-if="obj.tableData && !obj.error" :data="obj.tableData" border style="width: 100%">
                        <el-table-column prop="desc" width="180"> </el-table-column>
                        <el-table-column prop="value"> </el-table-column>
                    </el-table>
                    <p v-if="obj.downloadLink">导入结果下载，有啥问题都可以在这里找到喔! 亲！<a style="color:#20a0ff;" :href="obj.downloadLink +'?'+ Math.random()">「下载」</a></p>
                  </div>
                </div>
            </div>
        </el-upload>
      </el-dialog>
    </div>
    <SelectSite v-if="switchSite" @changeLoading="changeLoading"></SelectSite>
    <transition enter-active-class="bounceInRight" leave-active-class="bounceOutRight" v-on:after-leave="afterLeave">
      <CustomExportFilter v-loading.body="exportLoding" class="animated" v-if="showExportFilter" @export="exportSubmit" @cancel="exportCancel"></CustomExportFilter>
    </transition>
  </div>
</template>

<style lang="scss">
  @import '../scss/index';
    .echarts {
        height: 300px
    }

    .customs {
      .error {
        color: red;
      }
    }
    .btn-group {
      overflow: hidden;

      button {
        float: left;
      }
    }

    .content-main{
      height: 0;
      position: relative;
      float: left;
      min-height: 100%;
      width: 85%;
    }

    .short {
      max-width: 300px;
    }

    .right-content{
      padding-left: 20px;
      margin-top: 70px;
      padding-bottom: 100px;
      width: 99%;
      overflow-x: hidden;
      overflow-y: auto;
    }

    .echart-line{
      width: 100%;
      height: 400px;
    }

    .bread-ico {
      float: left;
      margin-right: 8px;
      margin-top: -8px;
      width: 30px;

      .fa-icon {
        width: 100%;
        height: 100%;
      }
    }

    .right-content {
      .el-tabs__header {
        margin-bottom: 0;
      }
      .el-tab-pane {
        padding-top: 15px;
      }
      .el-tabs__content {
        // height:  30rem;
        overflow-y: auto!important;
      }
    }

    .badge-list .el-badge {
      margin-right: 40px;
    }

    .scroll {
      width: 99%;
      overflow: hidden;
      overflow-y: auto;
    }

    .import-item {
      border-bottom: 1px solid rgb(223, 230, 236);
    }

    .short.el-select {
      min-width: 300px;
    }

    .el-input.short-filter-input {
      width: 160px;
    }

    .filter-body .filter-item {
      float: left;
      .el-input__inner {
        height: 28px;
      }

      &.mgl {
        margin-left: 10px;
      }

      &.el-pagination {
        padding: 0;
      }
    }
</style>

<script>
import Header from 'components/AdminHeader'
import LeftSideBar from 'components/LeftSideBar'
import SelectSite from 'components/SelectSite'
import Customs from 'components/Customs'
import EditCustom from 'components/EditCustom'
import CustomProfile from 'components/CustomProfile'
import ExportCustoms from 'components/ExportCustoms'
import CustomExportFilter from 'components/CustomExportFilter'

import { Col } from 'element-ui'
import { mapState, mapActions } from 'vuex'
import { Popover, Breadcrumb, BreadcrumbItem,
  Tabs, TabPane, Button, Dialog, Upload, Table,
  TableColumn, Pagination, Form, FormItem, Select, Input, Option } from 'element-ui'
import Config from '../config/common'
import Icon from 'vue-awesome/components/Icon.vue'
import 'vue-awesome/icons/wpexplorer'
import commonFilter from '../common/customs'

export default {
  data () {
    return {
      customClass: 'partloading',
      customData: [],
      customId: null,
      showExportFilter: false,
      loading: false,
      showUserPanel: false,
      docHeight: window.innerHeight + 'px',
      screenWidth: document.body.clientWidth,
      resize: false,
      activeName: 'customs',
      uploadDialog: false,
      uploadAction: '',
      fileList: [],
      exportLoding: false,
      filterData: {
        channel_id: null
      },
      exportTime: '',
      isInit: false,
      tabHeight: 500,
      responseList: {},
      currentPage: 1,
      customDetail: {},
      showFileList: false
    }
  },

  watch: {
    routeName (routeName) {
      console.log(routeName, 'routeName')
      this.activeName = routeName
    },
    screenWidth (val) {
      if (!this.timer) {
        this.screenWidth = val
        this.timer = true
        const that = this

        setTimeout(function () {
          that.resize = !that.resize
          that.timer = false
        }, 400)
      }
    },
    switchSite (value) {
      if (value === false) {
        this.loading = true
        setTimeout(() => {
          this.initialize()
        }, 2000)
      }
    },
    uploadDialog (value) {
      console.log(value)
      if (value === false) {
        this.emptyDatas()
        this.getCustoms()
      }
      this.tableData = []
      this.fileList = []
      this.responseList = {}
        // this.$refs.upload.clearFiles()
      // }
    },
    dataDictionary (val) {

    }
  },
  methods: {
    changeLoading (loading) {
      this.loading = loading
      console.log('changeLoading')
    },
    afterLeave () {
      console.log('afterLeave')
      if (this.exportStatus === true) {
        if (this.routeName !== 'export-customs') {
          this.$router.push({ name: 'export-customs' })
        } else {
          this.exportTime = Math.random()
        }
        this.exportStatus = false
      }
    },
    exportSubmit (status) {
      this.exportStatus = status
      this.showExportFilter = false
    },
    exportCancel (status) {
      this.exportStatus = status
      this.showExportFilter = false
    },
    handleSizeChange (val) {
      this.queryData['page_size'] = val
      this.page_size = val
      // hack
      this.setSizeInputVal(val)
      console.log(`每页 ${val} 条`)
      this.emptyDatas()
      this.getCustoms()
    },
    changeFilterData () {
      if (this.filterData.channel_id && this.filterData.channel_id.replace(' ', '')) {
        this.emptyList()
        this.getCustoms()
      } else {
        console.debug('no filter data')
        this.emptyDatas()
        this.getCustoms()
      }
    },
    emptyList () {
      this.list = []
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.saveCustom(this.customDetail).then((response) => {
            if (response.data.errcode === 0) {
              this.$router.push({ path: '/customs/' + this.customId })
              this.isEdit = false
              this.activeName = 'profile-detail'
              this.initCustom(this.customId)
              this.emptyDatas()
              this.getCustoms()
            }
          }).catch((err) => {
            console.log(err)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    setSizeInputVal (val) {
      const sizeInput = this.$refs.pagination.$el.getElementsByClassName('el-input__inner')[0]
      val = val + ' ' + '条/页'
      sizeInput.value = val
    },
    handleCurrentChange (val) {
      // if (this.isInit === false && parseInt(this.$route.query.page_index)) {
      //   val = parseInt(this.$route.query.page_index)
      //   this.currentPage = val
      //   this.isInit = true
      //   return
      // }
      this.queryData['page_index'] = val
      console.log(`当前页: ${val}`)
      this.emptyDatas()
      this.getCustoms()
    },
    handleClick (tab, event) {
      this.$router.push({ name: this.activeName })
      console.log(tab, this.activeName)
    },
    view ($scope) {
      this.initCustom($scope.row.id)
      this.$router.push({ path: '/customs/' + $scope.row.id })
      this.customId = $scope.row.id
      this.activeName = 'profile-detail'
    },
    editCustom ($scope) {
      this.customDetail = {}
      this.$router.push({ path: '/customs/' + $scope.row.id, query: { type: 'edit' }})
      this.customId = $scope.row.id
      this.activeName = 'profile-edit'
      this.isEdit = true
      this.initCustom($scope.row.id)
    },
    emptyDatas () {
      this.list = []
      this.filterData = {}
    },
    reverse (object) {
      var NewObj = {}
      var keysArr = Object.keys(object)
      for (var i = keysArr.length - 1; i >= 0; i--) {
        NewObj[keysArr[i]] = object[keysArr[i]]
      }
      return NewObj
    },
    filterPage (value, row) {
      console.log(value, row)
      return row.page_index === value
    },
    removeEmptyValues (dataObj) {
      var freshObject = {}
      for (const key in dataObj) {
        if (dataObj[key]) freshObject[key] = dataObj[key]
      }
      return freshObject
    },
    getCustoms (params) {
      this.loading = true
      const filterData = this.removeEmptyValues(this.filterData)
      const queryData = Object.assign({}, filterData, this.queryData, params || {})
      this.requestCustoms(queryData).then((response) => {
        const resData = response.data
        this.initPageFilters(resData.results)
        if (resData.errcode === 0 && resData.results && resData.results.data) {
          this.list = response.data.results.data
          // this.queryData['page_index'] = resData.results.currentPage
          this.total = resData.results.total
          this.currentPage = resData.results.current_page
          console.log('resData.results', this.currentPage, resData)
        } else {
          console.log('空数据')
        }
        this.loading = false
      }).catch((error) => {
        // console.log(error)
        console.log(error)
        this.loading = false
      })
    },
    initPageFilters (pageData) {
      const totalPage = Math.ceil(pageData['total'] / this.queryData.page_size)
      for (let i = 1; i <= totalPage; i++) {
        this.filters.push({
          value: i,
          text: i
        })
      }
    },
    initCustom (id) {
      this.getCustom({ id: id }).then((response) => {
        console.log(response.data.errcode)
        if (response.data.errcode === 0) {
          this.customDetail = response.data.results
          this.customData = this.formateCustom(this.customDetail)
        }
        this.loading = false
      }).catch((err) => {
        console.log(err)
        this.loading = false
      })
    },
    succesUpload (response, file, fileList) {
      const results = response.results
      const all = results.success + results.failed
      const data = [
        {
          'desc': '总条数',
          'value': all + '条'
        },
        {
          'desc': '失败条数',
          'value': results.failed + '条'
        },
        {
          'desc': '成功条数',
          'value': results.success + '条'
        }
      ]
      console.log('results', results)
      this.responseList = this.reverse(Object.assign({},
        this.responseList, {
          [file.name]: {
            file: file,
            tableData: data,
            error: response.errcode !== 0,
            code: response.errcode,
            msg: response.errmsg,
            downloadLink: results.download_link
          }
        }))
    },
    failedUpload (err, file, fileList, c) {
      console.log(err, file, fileList, c)
      this.responseList = this.reverse(Object.assign({},
        this.responseList, {
          [file.name]: {
            file: file,
            error: err,
            code: 10000,
            msg: '文件内容不合法',
            downloadLink: err.download_link
          }
        }))
    },
    initialize () {
      const windowHeight = window.innerHeight
      const offsetTop = this.$refs['tabpaneContainer'].offsetTop
      this.tabHeight = windowHeight - offsetTop - 110
      // this.loading = true
    },
    ...commonFilter,
    ...mapActions({
      requestCustoms: 'getCustoms',
      getDictionary: 'getDictionary',
      getCustom: 'getCustom',
      saveCustom: 'saveCustom',
      updateMenuIndex: 'updateMenuIndex',
    })
  },
  mounted: function () {
    this.customId = this.$route.params.id
    this.activeName = this.routeName
    this.uploadAction = Config.CRM_API_HOST + '/users/' + this.token + '/import'
    // this.setSizeInputVal(this.queryData.page_size)
    this.getDictionary()
    this.updateMenuIndex('customs')
    this.initialize()

    window.onresize = () => {
      return (() => {
        window.screenWidth = document.body.clientWidth
        this.screenWidth = window.screenWidth
      })()
    }
  },

  components: {
    ELHeader: Header,
    LeftSideBar: LeftSideBar,
    Customs: Customs,
    EditCustom: EditCustom,
    CustomProfile: CustomProfile,
    CustomExportFilter: CustomExportFilter,
    ExportCustoms: ExportCustoms,
    [Popover.name]: Popover,
    [Breadcrumb.name]: Breadcrumb,
    [Tabs.name]: Tabs,
    [TabPane.name]: TabPane,
    [BreadcrumbItem.name]: BreadcrumbItem,
    [Button.name]: Button,
    [Dialog.name]: Dialog,
    [Upload.name]: Upload,
    [Table.name]: Table,
    [TableColumn.name]: TableColumn,
    [Pagination.name]: Pagination,
    [Form.name]: Form,
    [Select.name]: Select,
    [Input.name]: Input,
    [Option.name]: Option,
    [FormItem.name]: FormItem,
    SelectSite,
    'el-col': Col,
    'icon': Icon
  },
  computed: {
    ...mapState({
      token: state => state.auth.user.token,
      dataDictionary: state => state.custom.data_dictionary,
      switchSite: state => state.custom.switch_site,
      route: state => state.route,
      path: state => state.route.path,
      routeName: state => state.route.name === 'home' ? 'normal-customs' : state.route.name
    })
  }
}

</script>
